package com.jun.controller;

import com.jun.entity.*;
import com.jun.service.*;
import com.jun.serviceimpl.AdminServiceImpl;
import com.jun.utils.MD5Utils;
import com.jun.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@CrossOrigin
@RequestMapping("admin") //管理员的控制层
@Slf4j
public class AdminController {
    @Autowired
    AdminServiceImpl adminService;
    @Autowired
    CookieService cookieService;
    @Autowired
    OperationService operationService;
    @Autowired
    UserService userService;
    @Autowired
    UserConsumeService userConsumeService;
    @Autowired
    MemberConsumeService memberConsumeService;
    @Autowired
    ConsumeService consumeService;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
    static String mac = "";
    static {
        {
            try {
                mac = Utils.getLocalMac(InetAddress.getLocalHost());
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }
    }

    @PostMapping("/login")   //管理员登录
    public Map<String,Object> login(@RequestBody Map<String,Object> map){    //传入用户名和密码
        HashMap<String, Object> hashMap = new HashMap<>();
        String username = (String) map.get("username");
        String pwd = (String) map.get("password");
        String password = MD5Utils.getMD5String(pwd);
        Boolean remeberMe = (Boolean) map.get("rememberMe");
        try{
            Subject subject = SecurityUtils.getSubject();   //获取当前用户
            UsernamePasswordToken token=new UsernamePasswordToken(username,password);   //封装登录的信息
            subject.login(token);   //用shiro来进行安全登录
            Admin admin = adminService.getUserById(username);
            Session session = subject.getSession();
            session.setAttribute("admin",admin);
            hashMap.put("state",true);
            log.info("登录成功!");
            hashMap.put("msg","登录成功！");
            Date date = new Date();
            String outtime = simpleDateFormat.format(new Date(date.getTime() + 1 * 24 * 60 * 60 * 1000));//过期时间
            Cookie searchCookieByMac = cookieService.searchCookieByMac(mac); //查看数据库有没有本机的cookie
            if(searchCookieByMac == null){
                if(remeberMe){
                    Cookie cookie = new Cookie(username, pwd, simpleDateFormat.format(date), outtime,mac);
                    int i = cookieService.insertCookie(cookie);//插入一条cookie
                    if(i==1){
                        log.info("插入一条cookie");
                    }else{
                        log.info("插入一条cookie失败");
                    }
                }
            }else{
                if(!searchCookieByMac.getPassword().equals(pwd)){
                    int i = cookieService.deleteCookieByMac(mac);
                    if(i==1){
                        log.info("删除一条cookie======》"+mac);
                        Cookie cookie = new Cookie(username, pwd, simpleDateFormat.format(date), outtime,mac);
                        int i1 = cookieService.insertCookie(cookie);//插入一条cookie
                        if(i1==1){
                            log.info("插入一条cookie");
                        }else{
                            log.info("插入一条cookie失败");
                        }
                    }
                }
            }
        }catch (UnknownAccountException e) {
            hashMap.put("state",false);
            log.info("用户名错误!");
            hashMap.put("msg","用户名错误");
        }catch (IncorrectCredentialsException e) {
            hashMap.put("state",false);
            log.info("密码错误!");
            hashMap.put("msg","密码错误");
        }


        return hashMap;

    }

    @PostMapping("/remember")    //记住密码
    public Map<String,Object> remember(){
        HashMap<String, Object> hashMap = new HashMap<>();
        Cookie cookie = cookieService.searchCookieByMac(mac);
        if(cookie == null){
            hashMap.put("state",false);
            return hashMap;
        }
        String outtime = cookie.getOuttime();
        try {
            long parse = simpleDateFormat.parse(outtime).getTime();   //获取cookie失效时间
            long currentTime = new Date().getTime();    //当前时间
            if(parse < currentTime){
                int i = cookieService.deleteCookieByMac(mac);
                if(i == 1){
                    log.info("删除失效cookie");
                    hashMap.put("state",false);
                }
            }else{
                hashMap.put("state",true);
                hashMap.put("username",cookie.getUsername());
                hashMap.put("password",cookie.getPassword());
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return hashMap;
    }

    @PostMapping("/findPassWord")   //找回密码
    public Map<String,Object> findPassWord(@RequestBody Map<String,Object> map){
        Map<String,Object> maps = new HashMap<>();
        String tellphone = (String) map.get("tellphone");
        Admin admin = adminService.getUserByTellPhone(tellphone);   //查找数据库是否存在用户
        if(admin == null){
            maps.put("state",false);
            maps.put("msg","该用户未注册！");
            log.info("找回密码---该用户未注册");
            return maps;
        }
        String password = MD5Utils.getMD5String((String) map.get("password")); //要修改的密码
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("password",password);
        hashMap.put("id",admin.getId());
        int i = adminService.updateAdminPassWord(hashMap);
        if(i == 1){
            maps.put("state",true);
            maps.put("msg","修改成功！请重新登录！");
            log.info("找回密码---密码修改成功！");
            return maps;
        }else{
            maps.put("state",false);
            maps.put("msg","修改失败！");
            log.info("找回密码---密码修改失败！");
            return maps;
        }
    }

    @PostMapping("/logout") //退出登录
    public Map<String,Object> logout(){
        HashMap<String, Object> hashMap = new HashMap<>();
        SecurityUtils.getSubject().logout();
        log.info("退出登录！");
        hashMap.put("state",true);
        return hashMap;
    }



    @PostMapping("/findUser")   //查询管理员
    public Map<String,Object> findUseByTellPhone(@RequestParam String tellphone){
        HashMap<String, Object> hashMap = new HashMap<>();
        Admin admin = adminService.getUserByTellPhone(tellphone);
        if(null == admin){
            hashMap.put("msg","查询失败！");
            log.info("查询管理员失败！");
            hashMap.put("state",false);
            return hashMap;
        }
        hashMap.put("state",true);
        log.info("查询管理员成功！");
        hashMap.put("admin",admin);
        return hashMap;
    }

    @PostMapping("/modifyPassword") //修改密码
    public Map<String,Object> modifyPassword(@RequestBody Map<String,Object> maps ){
        String newPassword = (String) maps.get("password");
        HashMap<String, Object> hashMap = new HashMap<>();
        Session session = SecurityUtils.getSubject().getSession();//查看用户是否还存在
        Admin admin = (Admin) session.getAttribute("admin");
        if(admin == null){
            hashMap.put("state",false);
            hashMap.put("msg","修改密码失败！请重新登录");
            log.info("修改密码失败！请重新登录");
            return hashMap;
        }
        String password = MD5Utils.getMD5String(newPassword);
        String id = admin.getId();
        Map<String,Object> map = new HashMap<>();
        map.put("id",id);
        map.put("password",password);
        int i = adminService.updateAdminPassWord(map);
        if(i == 1){
            hashMap.put("state",true);
            hashMap.put("msg","修改成功，请重新登录！");
            log.info("修改成功，请重新登录！");
            log.info("移除session，重新登录");
            session.removeAttribute("admin");   //移除session，重新登录
            return hashMap;
        }else{
            hashMap.put("state",true);
            hashMap.put("msg","修改密码失败！");
            log.info("修改密码失败！");
            return hashMap;
        }

    }

    @PostMapping("/getAllUser") //获取所有会员信息
    public Map<String,Object> getAllUser(){
        Map<String,Object> map = new HashMap<>();
        ArrayList<User> allUser = userService.getAllUser(); //获取所有会员信息
        if(allUser == null){
            log.info("会员表为空！");
        }
        map.put("users",allUser);
        map.put("state",true);
        log.info("输出会员信息表！");
        return map;
    }

    @PostMapping("/timesReduce")    //减少剪发。。。的次数
    public Map<String,Object> timesReduce(@RequestBody Map<String,Object> map){
        String tellphone = (String) map.get("tellphone");    //电话号码
        String type = (String) map.get("type");    //操作类型
        String time = simpleDateFormat.format(new Date());
        String operation = type + "次数-1";
        User user = userService.getUserByTellPhone(tellphone);  //得到用户
        HashMap<String, Object> maps = new HashMap<>();
        HashMap<String, Object> hashMap = new HashMap<>();
        int haircut = user.getHaircut();    //剪发次数
        int perm = user.getPerm();  //烫发次数
        int wash_protect = user.getWash_protect();  //护理次数
        int hairroot = user.getHairroot();  //补发根次数
        int colour = user.getColour();  //染发次数
        int wash = user.getWash();  //洗发次数
        int black = user.getBlack();    //黑油次数
        switch (type){
            case "剪发":haircut =haircut -1;break;
            case "烫发":;perm = perm -1;break;
            case "护理":wash_protect = wash_protect -1;break;
            case "补发根":hairroot = hairroot -1;break;
            case "染发":colour = colour -1;break;
            case "洗发":wash = wash -1;break;
            case "黑油":black = black -1;break;
        }
        maps.put("haircut",haircut);
        maps.put("perm",perm);
        maps.put("wash_protect",wash_protect);
        maps.put("hairroot",hairroot);
        maps.put("colour",colour);
        maps.put("wash",wash);
        maps.put("black",black);
        maps.put("tellphone",tellphone);
        int i = userService.updateUserTimesByTellPhone(maps);
        if(i==1){
            int c = operationService.insertOperation(new Operation(user.getId(), user.getUsername(), user.getSex(),
                    user.getTellphone(), user.getType(), operation, user.getRegisttime(), time));
            if(c==1){
                log.info("插入一条会员操作记录"+operation);
            }
            hashMap.put("state",true);
            HashMap<String, Object> hashMap1 = new HashMap<>();
            hashMap1.put("tellphone",tellphone);
            hashMap1.put("latest_operating_time",time);
            int b = userService.updateUserTimeByTellPhone(hashMap1);
            if(b==1){
                log.info("更新会员最新操作时间成功！");
            }else{
                log.info("更新会员最新操作时间失败！");
            }
        }else{
            hashMap.put("state",false);
        }
        return hashMap;
    }

    @PostMapping("/deleteUser") //删除会员
    public Map<String,Object> deleteUser(@RequestBody Map<String,Object> map){
        HashMap<String, Object> hashMap = new HashMap<>();
        String tellphone = (String) map.get("tellphone");    //得到电话号码
        int i = userService.deleteUserByTellPhone(tellphone);
        if(i == 1){
            hashMap.put("state",true);
            hashMap.put("msg","删除成功！");
            log.info("删除会员成功！");
        }else{
            hashMap.put("state",false);
            hashMap.put("msg","删除失败！");
            log.info("删除会员失败！");
        }
        return hashMap;
    }

    @PostMapping("/todayProfit")    //今日的收益
    public Map<String,Object> todayProfit(){
        HashMap<String, Object> hashMap = new HashMap<>();
        String time = simpleDateFormat2.format(new Date())+"%";
        String consume = consumeService.getOneConsume(time); //获取今天的总消费
        String[] week = {"星期一","星期二","星期三","星期四","星期五","星期六","星期日"};
        double result = 0;
        if(consume!=null)result += Double.parseDouble(consume);
        BigDecimal bg = new BigDecimal(result);
        double rs = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        String today = "";
        try {
            int day = Utils.dayForWeek(simpleDateFormat.format(new Date()));    //今天星期几
            today = week[day-1];
        } catch (Exception e) {
            e.printStackTrace();
        }
        hashMap.put("today",today);
        hashMap.put("state",true);
        hashMap.put("result",rs);
        log.info("获取今日的总收益！"+rs);
        return hashMap;
    }

    @PostMapping("/monthProfit")    //一个月之内的收益
    public Map<String,Object> monthProfit(@RequestBody Map<String,Object> map){
        String startTime = (String) map.get("startTime")+" 00:00:00";
        String endTime = (String) map.get("endTime")+" 00:00:00";
        HashMap<String, Object> hashMap = new HashMap<>();

        try {
            long parse = simpleDateFormat.parse(startTime).getTime(); //开始时间
            long parse2 = simpleDateFormat.parse(endTime).getTime();  //结束时间
            ArrayList<Double> result = new ArrayList<>();
            for(long i =parse;i<=parse2;i+=24*60*60*1000){
                double rs = 0;
                String format = simpleDateFormat2.format(new Date(i))+"%";  //要查询的日期
                String oneDayConsume = consumeService.getOneConsume(format);
                if(oneDayConsume!=null){
                    rs += Double.parseDouble(oneDayConsume);
                }
                BigDecimal bg = new BigDecimal(rs);
                double rsu = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
               result.add(rsu);
            }
            hashMap.put("result",result);
            hashMap.put("state",true);
            log.info("查询一个月之内的收益！");

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return hashMap;

    }

    @PostMapping("/yearProfit") //过去20年的收益
    public Map<String,Object> yearProfit(){
        HashMap<String, Object> hashMap = new HashMap<>();
        int year = new Date().getYear()+1900;   //今年的年份
        ArrayList<Double> result = new ArrayList<>();
        ArrayList<Integer> years = new ArrayList<>();
        for(int i=0;i<20;i++){
            years.add(year);
            double rs = 0;
            String time = year+"%";
            String oneConsume = consumeService.getOneConsume(time); //得到一年的总收益
            if(oneConsume!=null){
                rs+=Double.parseDouble(oneConsume);
            }
            BigDecimal bg = new BigDecimal(rs);
            double rsu = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            result.add(rsu);
            year--;
        }
        Collections.reverse(years);
        Collections.reverse(result);
        hashMap.put("state",true);
        hashMap.put("years",years);
        hashMap.put("result",result);
        log.info("查询20年之内的收益");
        return hashMap;
    }

    @PostMapping("/weekProfit") //这周的收益
    public Map<String,Object> weekProfit(){
        HashMap<String, Object> hashMap = new HashMap<>();
        String[] week = {"周一","周二","周三","周四","周五","周六","周日"};
        ArrayList<String> weeks = new ArrayList<>();
        ArrayList<Double> result = new ArrayList<>();
        long date = new Date().getTime();   //现在的时间
        try {
            int day = Utils.dayForWeek(simpleDateFormat.format(new Date()));    //今天星期几
            int temp = day;
            for(int i=1;i<=temp;i++){
                double rs = 0;
                weeks.add(week[i-1]);
                String time = simpleDateFormat2.format(date)+"%";
                String oneConsume = consumeService.getOneConsume(time); //一天的消费
                if(oneConsume!=null){
                    rs += Double.parseDouble(oneConsume);
                }
                BigDecimal bg = new BigDecimal(rs);
                double rsu = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                result.add(rsu);
                date -= 24*60*60*1000;
            }
            Collections.reverse(result);
            hashMap.put("weeks",weeks);
            hashMap.put("result",result);
            hashMap.put("state",true);
            log.info("查询一周的收益");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return hashMap;
    }

    @PostMapping("/weekProfit2")    //这周的收益，分为会员和普通用户
    public Map<String,Object> weekProfit2(){
        HashMap<String, Object> hashMap = new HashMap<>();
        long end = new Date().getTime(); //现在的时间--结束的时间
        String endTime = simpleDateFormat2.format(end)+" 23:59:59";   //结束时间
        try {
            int day = Utils.dayForWeek(endTime); //今天星期几
            long start = end - (day-1)*24*60*60*1000;   //起始时间
            String startTime = simpleDateFormat2.format(start)+" 00:00:00"; //起始时间
            HashMap<String, Object> maps = new HashMap<>();
            maps.put("startTime",startTime);
            maps.put("endTime",endTime);
            String memberProfit = memberConsumeService.searchConsumeByInterval(maps);//会员收益
            String userProfit = userConsumeService.searchUserConsumeByInterval(maps);//普通用户收益
            if(memberProfit==null){
                memberProfit = "";
            }
            if(userProfit==null){
                userProfit = "";
            }
            hashMap.put("memberProfit",memberProfit);
            hashMap.put("userProfit",userProfit);
            hashMap.put("state",true);
            log.info("查询这周的收益，分为会员和普通用户");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return hashMap;
    }









}
